package com.smiier.skin.ui;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.o.app.adapter.IItemView;
import cn.o.app.adapter.OAdapter;
import cn.o.app.adapter.OItemView;
import cn.o.app.event.listener.OnSelectedChangeListener;
import cn.o.app.json.JsonUtil;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.ui.OImageView;
import cn.o.app.ui.OTab;
import cn.o.app.util.OUtil;

import com.evan.common.pullrefresh.PullToRefreshBase;
import com.evan.common.pullrefresh.PullToRefreshBase.OnRefreshListener;
import com.evan.common.pullrefresh.PullToRefreshListView;
import com.lidroid.xutils.BitmapUtils;
import com.smiier.skin.AddPatientActivity;
import com.smiier.skin.PatientOfDoctorInfo;
import com.smiier.skin.PersonHomeActivity;
import com.smiier.skin.R;
import com.smiier.skin.SearchActivity;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.net.RelationshipGetListTask;
import com.smiier.skin.net.RelationshipGetListTask.RelationshipGetListRequest;
import com.smiier.skin.net.RelationshipGetListTask.RelationshipGetListResponse;
import com.smiier.skin.net.entity.RelationShip;
import com.smiier.skin.net.entity.User;
import com.smiier.skin.net.entity.UserWrapper;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;

@SuppressWarnings("deprecation")
public class PatientOfDoctorFragment extends BasicFragment {

	protected PullToRefreshListView mListView;
	protected OTab mTab;
	protected ImageView mBtnAddPatient;

	protected PatientOfDoctorAdapter mAdapter;

	protected boolean mInited;
	protected Long mStartRSUid;
	protected int mPageIndex;
	protected Long mRSSource;

	protected BitmapUtils mBitmapUtils;

	protected Drawable mDrawableMale;
	protected Drawable mDrawableFemale;

	protected Drawable mDrawableOffline;
	protected Drawable mDrawableOnline;
	protected Drawable mDrawableProject;
	RelativeLayout mTopBar;

	public PatientOfDoctorFragment(Context context) {
		super(context);
	}

	public PatientOfDoctorFragment(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public PatientOfDoctorFragment(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		setContentView(R.layout.fragment_patient_of_doctor);
		mTopBar = findViewById(R.id.top_bar, RelativeLayout.class);
		mBitmapUtils = new BitmapUtils(getContext());
		Resources res = this.getContext().getResources();
		mDrawableMale = res.getDrawable(R.drawable.sex_male);
		mDrawableFemale = res.getDrawable(R.drawable.sex_female);
		mDrawableOffline = res.getDrawable(R.drawable.source_from_offline);
		mDrawableOnline = res.getDrawable(R.drawable.source_from_online);
		mDrawableProject = res.getDrawable(R.drawable.source_from_project);

		mListView = this.findViewById(R.id.list, PullToRefreshListView.class);
		mTab = this.findViewById(R.id.tab_bar, OTab.class);
		mBtnAddPatient = this.findViewById(R.id.add_patient, ImageView.class);

		mAdapter = new PatientOfDoctorAdapter();
		mListView.setAdapter(mAdapter);

		mListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				mAdapter.setDataProvider(null);
				mAdapter.notifyDataSetChanged();
				mStartRSUid = null;
				loadData();
			}

			@Override
			public void onPullUpToLoadMore(
					PullToRefreshBase<ListView> refreshView) {
				loadData();
			}
		});

		// tiem的点击事件
		mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
			/*	try {*/
					/*Intent intent = new Intent(getContext(),
							PatientOfDoctorInfo.class);*/
					
					User mUser = mAdapter.getItem(position).mUserData.User;
					
					CommonUtility.toPersonHomeActivity((Activity)getContext(), mUser);
					
					/*
					Intent intent = new Intent(getContext(),PersonHomeActivity.class);
					
					
					intent.putExtra(Constant.IDENTITY_KEY, JsonUtil
							.convert(mAdapter.getItem(position).mUserData));

					Log.i("testquestioninfo",
							"getData:" + (mAdapter.getItem(position).mUserData));
					startActivity(intent);*/

			/*	} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}*/

			}
		});

		mTab.setSelectedIndex(0);
		mTab.setOnSelectedChangeListener(new OnSelectedChangeListener() {

			@Override
			public void onChanged(View v, int index) {
				if (index == 1) {
					mRSSource = RelationShip.SOURCE_SAOMIAO;
				} else if (index == 2) {
					mRSSource = RelationShip.SOURCE_ONLINE;
				} else if (index == 3) {
					mRSSource = RelationShip.SOURCE_GENZONG;
				} else {
					mRSSource = null;
				}
				mAdapter.setDataProvider(null);
				mAdapter.notifyDataSetChanged();
				mPageIndex = 0;
				mStartRSUid = null;
				loadData();
			}
		});
		mTopBar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getContext(), SearchActivity.class);
				intent.putExtra(Constant.IDENTITY_KEY_1, false);
				startActivity(intent);
			}
		});
		mBtnAddPatient.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getContext(),
						AddPatientActivity.class);
				startActivity(intent);
			}
		});
	}

	@Override
	public void onResume() {
		super.onResume();

		Log.i("testload", "onResume.mInited:" + (!mInited));

		// if (!mInited) {
		loadData();
		// }
	}

	protected void loadData() {
		RelationshipGetListRequest req = new RelationshipGetListRequest();
		req.token = GlobalSettings.sToken;
		req.startrsuid = mStartRSUid;
		req.RSUser_Type = User.USER_TYPE_PATIENT;
		req.RSSource = mRSSource;
		req.pagesize = GlobalSettings.PAGE_SIZE;
		// req.pageIndex = ++mPageIndex;
		RelationshipGetListTask task = new RelationshipGetListTask();
		task.setRequest(req);

		Log.i("testload", "task.request");

		task.addListener(new NetTaskListener<RelationshipGetListTask.RelationshipGetListRequest, RelationshipGetListTask.RelationshipGetListResponse>() {

			@Override
			public void onException(
					INetTask<RelationshipGetListRequest, RelationshipGetListResponse> task,
					Exception e) {
				mListView.doComplete();
				e.printStackTrace();
				Log.i("testload", "task.onException");
			}

			@Override
			public void onComplete(
					INetTask<RelationshipGetListRequest, RelationshipGetListResponse> task,
					RelationshipGetListResponse response) {

				Log.i("testload", "task.onComplete");

				Log.i("testload", "loadData.onComplete:" + response);

				mListView.doComplete();
				if (response.ResultCode != 200) {
					return;
				}
				mInited = true;
				if (response.Res.Count == 0) {
					mListView.setContextEmptyType(true, 2);
				} else {
					mListView.setContextEmptyType(false, 2);
				}

				mListView.setHasMoreData(mAdapter.getCount()
						+ response.Res.Users.size() < response.Res.Count);
				List<PatientOfDoctorItem> dataItems = mAdapter
						.getDataProvider();
				dataItems = dataItems != null ? dataItems
						: new ArrayList<PatientOfDoctorFragment.PatientOfDoctorItem>();
				int size = response.Res.Users.size();
				for (int i = 0; i < size; i++) {
					PatientOfDoctorItem item = new PatientOfDoctorItem();
					// item.mUserData = response.Res.Users.get(i);

					Log.i("testload", "uid:" + response.Res.Users.get(i).Uid);

					UserWrapper addItem = new UserWrapper();

					addItem.FollowerCount = response.Res.Users.get(i).FollowerCount;
					addItem.Is_Follow = response.Res.Users.get(i).Is_Follow;
					addItem.RelationShip = response.Res.Users.get(i).RelationShip;
					Log.i("testload", "addData.RelationShip:"
							+ response.Res.Users.get(i).RelationShip);
					addItem.Uid = response.Res.Users.get(i).Uid;
					addItem.User = response.Res.Users.get(i).User;
					item.mUserData = addItem;
					boolean has = false;
					for (PatientOfDoctorItem pitem : dataItems) {
						if ((pitem.mUserData.User.Uid + "")
								.equals(item.mUserData.User.Uid + "")) {
							has = true;
							break;
						}
					}
					if (!has) {
						dataItems.add(item);
					}

				}

				/*
				 * if (size > 0) { mStartRSUid = response.Res.Users.get(size -
				 * 1).Relationship.RSID; }
				 */

				doInvalidateClass();

				Log.i("testload", "mAdapter.setDataProvider.dataItems:"
						+ (dataItems.size()));

				mAdapter.setDataProvider(dataItems);

			}
		});
		add(task);
	}

	protected void doInvalidateClass() {
		List<PatientOfDoctorItem> dataItems = mAdapter.getDataProvider();
		if (dataItems == null) {
			return;
		}
		for (PatientOfDoctorItem item : dataItems) {
			item.mCount4Class = null;
			item.mStart4Class = null;
			item.mEnd4Class = null;
		}
	}

	class PatientOfDoctorItem {
		public Integer mStart4Class;
		public Integer mEnd4Class;
		public Integer mCount4Class;
		protected UserWrapper mUserData;
	}

	class PatientOfDoctorAdapter extends OAdapter<PatientOfDoctorItem> {

		@Override
		public IItemView<PatientOfDoctorItem> getItemView() {

			return new PatientOfDoctorItemView(getContext());
		}

	}

	class PatientOfDoctorItemView extends OItemView<PatientOfDoctorItem> {
		protected View mTitleBar;
		protected TextView mTime;
		protected TextView mCount;
		protected View mTopLine;
		// protected View mBottomLine;
		protected OImageView mLogo;
		protected TextView mName;
		protected TextView mProfile;
		protected TextView mSourceFrom;

		protected int mBottomMarginLeft;

		public PatientOfDoctorItemView(Context context) {
			super(context);
		}

		@Override
		public void onCreate() {
			this.setContentView(R.layout.item_patient_of_doctor);
			mTitleBar = this.findViewById(R.id.title_bar, View.class);
			mTime = this.findViewById(R.id.time, TextView.class);
			mCount = this.findViewById(R.id.count, TextView.class);
			mTopLine = this.findViewById(R.id.top_line, View.class);
			// mBottomLine = this.findViewById(R.id.bottom_line, View.class);
			mLogo = this.findViewById(R.id.logo, OImageView.class);
			mName = this.findViewById(R.id.name, TextView.class);
			mProfile = this.findViewById(R.id.profile, TextView.class);
			mSourceFrom = this.findViewById(R.id.source_from, TextView.class);

			mBottomMarginLeft = (int) OUtil.dp2px(getContext(), 16);
		}

		@Override
		public void onResume() {

			if (mDataProvider.mCount4Class == null) {
				doInit4Class();
			}
			Date today = new Date();
			String timeStr = null;

			if (OUtil.isSameDay(today,
					mDataProvider.mUserData.RelationShip.CreateTime)) {
				timeStr = "今天";
			} else {
				mDataProvider.mUserData.RelationShip.CreateTime
						.setFormat("MM月dd日");
				timeStr = mDataProvider.mUserData.RelationShip.CreateTime
						.toString();
			}
			CommonUtility.displayHeadImage(mLogo, mBitmapUtils,
					GlobalSettings.SERVER_IMG_URL
							+ mDataProvider.mUserData.User.Pic
							+ GlobalSettings.IMG_SRC, getContext()
							.getResources(), mDataProvider.mUserData.User.Sex);
			mTime.setText(timeStr);
			mCount.setText("(" + mDataProvider.mCount4Class + "人)");
			String logoUrl = GlobalSettings.SERVER_IMG_URL
					+ mDataProvider.mUserData.User.Pic;
			if (logoUrl.lastIndexOf(".") == -1) {
				logoUrl += GlobalSettings.IMG_THUMB;
			}
			// mBitmapUtils.display(mLogo, logoUrl,
			// new OBitmapLoadCallBack<View>());
			mName.setText(mDataProvider.mUserData.User.Name);
			StringBuilder sb = new StringBuilder();
			if (mDataProvider.mUserData.User.Sex == User.SEX_MALE) {
				mName.setCompoundDrawablesWithIntrinsicBounds(null, null,
						mDrawableMale, null);
				sb.append("男,");
			} else if (mDataProvider.mUserData.User.Sex == User.SEX_FEMALE) {
				mName.setCompoundDrawablesWithIntrinsicBounds(null, null,
						mDrawableFemale, null);
				sb.append("女,");
			} else {
				mName.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
						null);
			}
			sb.append(today.getYear()
					- mDataProvider.mUserData.User.Birth.getYear());
			sb.append("岁");
			if (!OUtil.isEmpty(mDataProvider.mUserData.RelationShip.Diagnose)) {
				sb.append(",");
				sb.append(mDataProvider.mUserData.RelationShip.Diagnose);
			}
			mProfile.setText(sb.toString());
			if (mDataProvider.mUserData.RelationShip.RSSource == RelationShip.SOURCE_SAOMIAO) {
				mSourceFrom.setVisibility(View.VISIBLE);
				mSourceFrom.setText("线下导入");
				mSourceFrom.setCompoundDrawablesWithIntrinsicBounds(null, null,
						mDrawableOffline, null);
			} else if (mDataProvider.mUserData.RelationShip.RSSource == RelationShip.SOURCE_ONLINE
					|| mDataProvider.mUserData.RelationShip.RSSource == 0) {
				mSourceFrom.setVisibility(View.VISIBLE);
				mSourceFrom.setText("在线咨询");
				mSourceFrom.setCompoundDrawablesWithIntrinsicBounds(null, null,
						mDrawableOnline, null);
			} else if (mDataProvider.mUserData.RelationShip.RSSource == RelationShip.SOURCE_GENZONG) {
				// mSourceFrom.setVisibility(View.INVISIBLE);
				mSourceFrom.setVisibility(View.VISIBLE);
				mSourceFrom.setText("项目跟踪");
				mSourceFrom.setCompoundDrawablesWithIntrinsicBounds(null, null,
						mDrawableProject, null);
			} else {
				mSourceFrom.setVisibility(View.INVISIBLE);
			}
			if (mDataProvider.mStart4Class.equals(mPosition)) {
				mTitleBar.setVisibility(View.VISIBLE);
				mTopLine.setVisibility(View.GONE);
			} else {
				mTopLine.setVisibility(View.VISIBLE);
				mTitleBar.setVisibility(View.GONE);
			}
			/*
			 * if (mDataProvider.mCount4Class.equals(1)) {
			 * 
			 * mTopLine.setVisibility(View.GONE); } else {
			 * mTopLine.setVisibility(View.VISIBLE);
			 * 
			 * }
			 */
			/*
			 * RelativeLayout.LayoutParams bottomParams =
			 * (RelativeLayout.LayoutParams) mBottomLine .getLayoutParams(); if
			 * (bottomParams != null) { if
			 * (mDataProvider.mEnd4Class.equals(mPosition)) {
			 * bottomParams.setMargins(mBottomMarginLeft, 0, 0, 0); } else {
			 * bottomParams.setMargins(0, 0, 0, 0); }
			 * mBottomLine.setLayoutParams(bottomParams); }
			 */
		}

		protected void doInit4Class() {
			int start = mPosition;
			int end = mPosition;

			for (int i = mPosition - 1; i >= 0; i--) {
				PatientOfDoctorItem item = mAdapter.getItem(i);
				if (OUtil.isSameDay(item.mUserData.RelationShip.CreateTime,
						mDataProvider.mUserData.RelationShip.CreateTime)) {
					if (item.mCount4Class != null) {
						mDataProvider.mCount4Class = item.mCount4Class;
						mDataProvider.mStart4Class = item.mStart4Class;
						mDataProvider.mEnd4Class = item.mEnd4Class;
						break;
					}
				} else {
					start = i + 1;
					break;
				}
			}
			if (mDataProvider.mCount4Class != null) {
				return;
			}
			for (int i = mPosition + 1, size = mAdapter.getCount(); i < size; i++) {
				PatientOfDoctorItem item = mAdapter.getItem(i);
				if (OUtil.isSameDay(item.mUserData.RelationShip.CreateTime,
						mDataProvider.mUserData.RelationShip.CreateTime)) {
					if (item.mCount4Class != null) {
						mDataProvider.mCount4Class = item.mCount4Class;
						mDataProvider.mStart4Class = item.mStart4Class;
						mDataProvider.mEnd4Class = item.mEnd4Class;
						break;
					}
				} else {
					end = i - 1;
					break;
				}
			}
			if (mDataProvider.mCount4Class != null) {
				return;
			}
			mDataProvider.mCount4Class = (end - start) + 1;
			mDataProvider.mStart4Class = start;
			mDataProvider.mEnd4Class = end;
		}
	}

}
